<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2014 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace suifeng\builder;

use think\Request;

/**
 * 分页类
 */
class Pagination
{
    public $listRows = 20; // 列表每页显示行数
    public $parameter; // 分页跳转时要带的参数
    public $totalRows = 0; // 总行数
    public $rollPage = 7; // 分页栏每页显示的页数
    public $url; //当前链接URL

    public $pageVar; //分页参数名
    public $nowPage;

    // 分页显示定制
    private $config = array(
        'header' => '<span class="rows">共 %TOTAL_ROW% 条记录</span>',
        'prev'   => '<',
        'next'   => '>',
        'first'  => '<<',
        'last'   => '>>',
        'theme'  => '%FIRST%%UP_PAGE%%LINK_PAGE%%DOWN_PAGE%%END%',
        'info'   => '总共 %TOTAL% 条记录，显示第 %START% 到 %END% 条',
    );

    /**
     * 架构函数
     * @param array $totalRows  总的记录数
     * @param array $listRows  每页显示记录数
     * @param array $parameter  分页跳转的参数
     */
    public function __construct($totalRows = 0, $listRows = 20, $parameter = array())
    {
        $this->pageVar = 'page';//config('paginate.var_page'); //设置分页参数名称
        $this->totalRows = $totalRows; //设置总记录数
        $this->listRows  = $listRows; //设置每页显示行数
        $this->parameter = empty($parameter) ? $_GET : $parameter;
        $this->nowPage   = input($this->pageVar, 1);
        $this->nowPage   = $this->nowPage > 0 ? $this->nowPage : 1;
        if ($this->isWap()) {
            $this->rollPage = 3;
            $this->config['theme'] = '%UP_PAGE%%LINK_PAGE%%DOWN_PAGE%';
        }
    }

    /**
     * 定制分页链接设置
     * @param string $name  设置名称
     * @param string $value 设置值
     */
    public function setConfig($name, $value)
    {
        if (isset($this->config[$name])) {
            $this->config[$name] = $value;
        }
    }

    /**
     * 生成链接URL
     * @param  integer $page 页码
     * @return string
     */
    private function url($page)
    {
        return str_replace(urlencode('[page]'), $page, $this->url);
    }

    private function page($page, $text, $class, $enable)
    {
        if ($enable) {
            return '<li class="' . $class . '"><a href="' . $this->url($page) . '">' . $text . '</a></li>';
        } else {
            return '<li class="' . $class . '"><span>' . $text . '</span></li>';
        }
    }

    /**
     * 组装分页链接
     * @return string
     */
    public function show_pages()
    {
        if (0 == $this->totalRows || $this->totalRows <= $this->listRows) {
            return '';
        }

        // 如果没有设置url，则自动生成
        if (empty($this->url)) {
            $this->parameter[$this->pageVar] = '[PAGE]';
            $this->url = url(Request::instance()->action(), $this->parameter);
        }

        /* 计算分页信息 */
        $totalPages = ceil($this->totalRows / $this->listRows); //总页数
        if (!empty($totalPages) && $this->nowPage > $totalPages) {
            $this->nowPage = $totalPages;
        }

        /* 计算分页临时变量 */
        $now_cool_page      = $this->rollPage / 2;
        $now_cool_page_ceil = ceil($now_cool_page);

        //上一页
        $up_row  = $this->nowPage - 1;
        //$up_page = $up_row > 0 ? '<li><a class="prev" href="' . $this->url($up_row) . '">' . $this->config['prev'] . '</a></li>' : '';
        $up_page = $this->page($up_row > 0 ? $up_row : null, $this->config['prev'], 'prev', $up_row > 0);

        //下一页
        $down_row  = $this->nowPage + 1;
        //$down_page = ($down_row <= $totalPages) ? '<li><a class="next" href="' . $this->url($down_row) . '">' . $this->config['next'] . '</a></li>' : '';
        $down_page = $this->page($down_row <= $totalPages ? $down_row : null, $this->config['next'], 'prev', $down_row <= $totalPages);

        //第一页
        $the_first = '';
        if ($totalPages > $this->rollPage && ($this->nowPage - $now_cool_page) >= 1) {
            $the_first = '<li><a class="first" href="' . $this->url(1) . '">' . $this->config['first'] . '</a></li>';
        } else if ($totalPages > 10) {
            $the_first = $this->page(null, $this->config['first'], 'first', false);
        }

        //最后一页
        $the_end = '';
        if ($totalPages > $this->rollPage && ($this->nowPage + $now_cool_page) < $totalPages) {
            $the_end = '<li><a class="end" href="' . $this->url($totalPages) . '">' . $this->config['last'] . '</a></li>';
        } else if ($totalPages > 10) {
            $the_end = $this->page(null, $this->config['last'], 'last', false);
        }

        //数字连接
        $link_page = "";
        for ($i = 1; $i <= $this->rollPage; $i++) {
            if (($this->nowPage - $now_cool_page) <= 0) {
                $page = $i;
            } elseif (($this->nowPage + $now_cool_page - 1) >= $totalPages) {
                $page = $totalPages - $this->rollPage + $i;
            } else {
                $page = $this->nowPage - $now_cool_page_ceil + $i;
            }
            if ($page > 0 && $page != $this->nowPage) {

                if ($page <= $totalPages) {
                    $link_page .= $this->page($page, $page, 'num', true);
                } else {
                    break;
                }
            } else {
                if ($page > 0 && 1 != $totalPages) {
                    $link_page .= $this->page($page, $page, 'num active', true);
                }
            }
        }

        if ($link_page) {
            //if (!$up_page) {
            //    $up_page = '<li><a class="prev" href="#">没有了</a></li>';
            //}
            if (!$down_page) {
                $down_page = '<li><a class="next" href="#">没有了</a></li>';
            }
        }

        //替换分页内容
        $page_str = str_replace(
            array('%HEADER%', '%NOW_PAGE%', '%UP_PAGE%', '%DOWN_PAGE%', '%FIRST%', '%LINK_PAGE%', '%END%', '%TOTAL_ROW%', '%TOTAL_PAGE%'),
            array($this->config['header'], $this->nowPage, $up_page, $down_page, $the_first, $link_page, $the_end, $this->totalRows, $totalPages),
            $this->config['theme']);
        return "{$page_str}";
    }

    public function show_info()
    {
        if (0 == $this->totalRows) {
            return '';
        }

        $start = ($this->nowPage - 1) * $this->listRows + 1;
        $end = $start + $this->listRows - 1 < $this->totalRows ? $start + $this->listRows - 1: $this->totalRows;

        return str_replace(
            array('%START%', '%END%', '%TOTAL%'),
            array($start, $end, $this->totalRows),
            $this->config['info']);
    }

    /**
     * 检测是否使用手机访问
     * @access public
     * @return bool
     */
    public function isWap()
    {
        if (isset($_SERVER['HTTP_VIA']) && stristr($_SERVER['HTTP_VIA'], "wap")) {
            return true;
        } elseif (isset($_SERVER['HTTP_ACCEPT']) && strpos(strtoupper($_SERVER['HTTP_ACCEPT']), "VND.WAP.WML")) {
            return true;
        } elseif (isset($_SERVER['HTTP_X_WAP_PROFILE']) || isset($_SERVER['HTTP_PROFILE'])) {
            return true;
        } elseif (isset($_SERVER['HTTP_USER_AGENT']) && preg_match('/(blackberry|configuration\/cldc|hp |hp-|htc |htc_|htc-|iemobile|kindle|midp|mmp|motorola|mobile|nokia|opera mini|opera |Googlebot-Mobile|YahooSeeker\/M1A1-R2D2|android|iphone|ipod|mobi|palm|palmos|pocket|portalmmm|ppc;|smartphone|sonyericsson|sqh|spv|symbian|treo|up.browser|up.link|vodafone|windows ce|xda |xda_)/i', $_SERVER['HTTP_USER_AGENT'])) {
            return true;
        } else {
            return false;
        }
    }
}
